package com.zl.smartmall.library.listener;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;






import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.po.GZCommunity;
import com.zl.smartmall.library.po.GZCommunityInfo;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.PreferenceModel;

public abstract class GetMyCommunityAddressListener extends BaseListener {


	public abstract void onResponseSuccess(List<GZCommunityInfo> lists);
	
	@Override
	public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
		try {
			int ret = response.getInt("ret");
			switch (ret) {
			case 0:
				JSONObject result = response.getJSONObject("result");
				JSONArray items = result.getJSONArray("list");
				List<GZCommunityInfo> lists = new ArrayList<GZCommunityInfo>();
				for(int i = 0;i<items.length();i++){
					JSONObject item = items.getJSONObject(i);
					GZCommunityInfo info = new GZCommunityInfo();
					info.setPid(item.getInt("id"));
					info.setCmid(item.getInt("cmid"));
					info.setCommunityName(item.getString("community_name"));
					info.setHouseName(item.getString("house_name"));
					info.setStatus(item.getInt("selected"));
					info.setCurrentId(IAuth.getInstance().loadUserInfo().getUid());
				
					if(info.getStatus() == 1){
						PreferenceModel.putBoolean(Constants.PREFERENCE_KEY_HAS_COMMUNITY, true);
						PreferenceModel.putInt(Constants.PREFERENCE_KEY_COMMUNITY_ID, info.getCmid());
						PreferenceModel.putInt(Constants.PREFERENCE_KEY_HOUSEID, info.getPid());
						PreferenceModel.putString(Constants.PREFERENCE_KEY_COMMUNITY_NAME,  info.getHouseName().substring(0, info.getHouseName().indexOf(",")));
					}
					lists.add(info);
				}
				
				onResponseSuccess(lists);
				break;
			case 2:
				onOffline();
				break;
			case 4:
				onNoMoreData();
				break;

			default:
				break;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			onResponseFailed();
		}
	}
	
	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		super.onFailure(statusCode, headers, responseString, throwable);
		onResponseFailed();
	}
}
